package com.ailanyin.modules.flowable.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.ailanyin.common.database.result.CommonPage;
import com.ailanyin.modules.flowable.domain.bo.WfProcessBo;
import com.ailanyin.modules.flowable.domain.vo.WfDeployVo;
import com.ailanyin.modules.flowable.mapper.WfDeployFormMapper;
import com.ailanyin.modules.flowable.service.IWfDeployService;
import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/12/14 0014 上午 11:18
 */
@Service
public class WfDeployServiceImpl implements IWfDeployService {

    @Autowired
    private RepositoryService repositoryService;
    @Resource
    private WfDeployFormMapper deployFormMapper;

    @Override
    public CommonPage<WfDeployVo> queryPublishList(String processKey, Integer pageNum, Integer pageSize) {
        // 创建查询条件
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(processKey)
                .orderByProcessDefinitionVersion()
                .desc();
        long pageTotal = processDefinitionQuery.count();
        if (pageTotal <= 0) {
            return new CommonPage<>(new ArrayList<>(), 0);
        }
        // 根据查询条件，查询所有版本
        List<WfDeployVo> deployVoList = getWfDeployVos(pageNum, pageSize, processDefinitionQuery);
        return new CommonPage<>(deployVoList, pageTotal);
    }

    private List<WfDeployVo> getWfDeployVos(Integer pageNum, Integer pageSize, ProcessDefinitionQuery processDefinitionQuery) {
        int offset = pageSize * (pageNum - 1);
        List<ProcessDefinition> definitionList = processDefinitionQuery
                .listPage(offset, pageSize);

        List<WfDeployVo> deployVoList = new ArrayList<>(definitionList.size());
        for (ProcessDefinition processDefinition : definitionList) {
            String deploymentId = processDefinition.getDeploymentId();
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
            WfDeployVo vo = createVo(processDefinition);
            // 流程部署信息
            vo.setCategory(deployment.getCategory());
            vo.setDeploymentTime(deployment.getDeploymentTime());
            List<String> list = StrUtil.split(deployment.getName(), "-");
            vo.setModelVersion(list.get(list.size() - 1));
            deployVoList.add(vo);
        }
        return deployVoList;
    }

    @Override
    public CommonPage<WfDeployVo> queryPageList(WfProcessBo processBo, Integer pageNum, Integer pageSize) {

        // 流程定义列表数据查询
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
                .latestVersion()
                .orderByProcessDefinitionKey()
                .asc();
        createSearchQuery(processBo, processDefinitionQuery);
        long pageTotal = processDefinitionQuery.count();
        if (pageTotal <= 0) {
            return new CommonPage<>(new ArrayList<>(), pageTotal);
        }
        List<WfDeployVo> deployVoList = getWfDeployVos(pageNum, pageSize, processDefinitionQuery);

        return new CommonPage<>(deployVoList, pageTotal);

    }

    private WfDeployVo createVo(ProcessDefinition processDefinition) {
        WfDeployVo vo = new WfDeployVo();
        vo.setDefinitionId(processDefinition.getId());
        vo.setProcessKey(processDefinition.getKey());
        vo.setProcessName(processDefinition.getName());
        vo.setVersion(processDefinition.getVersion());
        vo.setCategory(processDefinition.getCategory());
        vo.setDeploymentId(processDefinition.getDeploymentId());
        vo.setSuspended(processDefinition.isSuspended());
        return vo;
    }

    private void createSearchQuery(WfProcessBo processBo, ProcessDefinitionQuery processDefinitionQuery) {
        if (StrUtil.isNotBlank(processBo.getProcessKey())) {
            processDefinitionQuery.processDefinitionKeyLike("%" + processBo.getProcessKey() + "%");
        }
        if (StrUtil.isNotBlank(processBo.getProcessName())) {
            processDefinitionQuery.processDefinitionNameLike("%" + processBo.getProcessName() + "%");
        }
        if (StrUtil.isNotBlank(processBo.getCategory())) {
            processDefinitionQuery.processDefinitionCategory(processBo.getCategory());
        }
        if (StrUtil.isNotBlank(processBo.getState())) {
            if (SuspensionState.ACTIVE.toString().equals(processBo.getState())) {
                processDefinitionQuery.active();
            } else if (SuspensionState.SUSPENDED.toString().equals(processBo.getState())) {
                processDefinitionQuery.suspended();
            }
        }
    }

    @Override
    public void updateState(String definitionId, String state) {
        if (SuspensionState.ACTIVE.toString().equals(state)) {
            // 激活
            repositoryService.activateProcessDefinitionById(definitionId, true, null);
        } else if (SuspensionState.SUSPENDED.toString().equals(state)) {
            // 挂起
            repositoryService.suspendProcessDefinitionById(definitionId, true, null);
        }
    }

    @Override
    public String queryBpmnXmlById(String definitionId) {
        return IoUtil.readUtf8(repositoryService.getProcessModel(definitionId));
    }

    @Override
    public void deleteByIds(List<String> deployIds) {
        for (String deployId : deployIds) {
            repositoryService.deleteDeployment(deployId, true);
            deployFormMapper.deleteByDeployId(deployId);
        }
    }
}
